<template>
  <el-dialog :append-to-body="true" fullscreen="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog"
             :title="isAdd ? '新增' : '编辑'"
             append-to-body width="40%">
    <div class="el-dialog-div">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" maxlength="20" style="width: 370px;"/>
        </el-form-item>
        <el-form-item label="主题图片" prop="themeImage">
          <el-upload
            class="avatar-uploader"
            :action="fileUploadUrl"
            :show-file-list="false"
            :on-success="themeHandleSuccess"
            :before-upload="beforeThemeUpload">
            <img v-if="themeImage" :src="themeUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="课程资源" prop="courseFile">
          <el-upload
            class="upload-demo"
            drag
            :action="fileUploadUrl"
            :on-success="resourceHandleSuccess"
            :before-upload="beforeResource"
            :file-list="courseFile">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="课程来源" prop="source">
          <el-input v-model="form.source" maxlength="20" style="width: 370px;"/>
        </el-form-item>
        <el-form-item label="课件学时(分钟)" prop="classHour">
          <el-input-number v-model.number="form.classHour" :min="0" :max="999" controls-position="right"/>
        </el-form-item>
        <el-form-item label="课程状态" prop="status">
          <el-select v-model="form.status" placeholder="课程状态">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程讲师" prop="teacherId">
          <el-select v-model="form.teacherId" filterable placeholder="请选择">
            <el-option
              v-for="item in teacherList"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属章节" prop="chapterId">
          <treeselect v-model="form.chapterId" :options="chapter" placeholder="选择章节"/>
        </el-form-item>
        <el-form-item label="所属分类" prop="typeId">
          <treeselect v-model="form.typeId" :options="courseType" placeholder="选择课程分类"/>
        </el-form-item>
        <el-form-item label="关联培训计划" prop="planId">
          <el-select v-model="form.planId" filterable placeholder="请选择">
            <el-option
              v-for="item in planList"
              :key="item.id"
              :label="item.planName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 10}"
            placeholder="请输入内容课程简介"
            v-model="form.courseDesc">
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { tree } from '@/api/business/chapter'
  import { add } from '@/api/business/course'
  import { findUser } from '@/api/business/user'
  import { typeTree } from '@/api/business/courseType'
  import { getPlanList } from '@/api/business/trainPlan'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    components: { Treeselect },
    props: {
      isAdd: {
        type: Boolean,
        required: true
      }
    },
    data() {
      return {
        fileUploadUrl: process.env.FILE_UPLOAD,
        loading: false,
        dialog: false,
        teacher: 'r_teacher',
        options: [{
          value: 0,
          label: '未上线'
        }, {
          value: 1,
          label: '已上线'
        }],
        courseType: [],
        chapter: [],
        teacherList: [],
        planList: [],
        themeImage: [],
        courseFile: [],
        themeUrl: null,
        form: {
          id: null,
          courseName: '',
          themeImage: '',
          source: '',
          courseFile: '',
          classHour: 0,
          courseDesc: '',
          teacherId: '',
          chapterId: '',
          typeId: '',
          planId: '',
          status: 0
        },
        rules: {
          courseName: [
            { required: true, message: '请输入课程名称', trigger: 'blur' }
          ],
          themeImage: [
            { required: true, message: '请上传课程主题图片', trigger: 'change' }
          ],
          courseFile: [
            { required: true, message: '请上传课程资源', trigger: 'change' }
          ]
        }

      }
    },
    methods: {
      cancel() {
        this.dialog = false
        this.themeImage = []
        this.courseFile = []
        this.form = {
          id: null,
          courseName: '',
          themeImage: '',
          source: '',
          courseFile: '',
          classHour: 0,
          courseDesc: '',
          teacherId: '',
          chapterId: '',
          typeId: '',
          planId: '',
          status: 0
        }
      },
      doSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.doAdd()
          }
        })
      },
      doAdd() {
        add(this.form).then(res => {
          this.$notify({
            title: '操作成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.$parent.init()
          this.cancel()
        }).catch(err => {
          this.loading = false
          console.log(err)
        })
      },
      beforeThemeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
      },
      themeHandleSuccess(response, file, fileList) {
        this.form.themeImage = []
        const uploadFile = {
          name: file.name,
          url: file.response
        }
        this.themeUrl = uploadFile.url
        this.form.themeImage.push(uploadFile)
        this.form.themeImage = JSON.stringify(this.form.themeImage)
        this.$refs.form.validateField('themeImage')
      },
      beforeResource(file) {
        const FILE_NAME = file.name
        if (FILE_NAME.substring(FILE_NAME.lastIndexOf('.')) !== '.mp4' &&
          FILE_NAME.substring(FILE_NAME.lastIndexOf('.')) !== '.MP4' &&
          FILE_NAME.substring(FILE_NAME.lastIndexOf('.')) !== '.avi' &&
          FILE_NAME.substring(FILE_NAME.lastIndexOf('.')) !== '.AVI') {
          this.$message.warning('仅支持.mp4.avi')
          return false
        }
      },
      resourceHandleSuccess(response, file, fileList) {
        this.form.courseFile = []
        const uploadFile = {
          name: file.name,
          url: file.response
        }
        this.form.courseFile.push(uploadFile)
        this.form.courseFile = JSON.stringify(this.form.courseFile)
        this.$refs.form.validateField('courseFile')
      },
      initData() {
        this.getChapter()
        this.getCourseType()
        this.getTeacher()
        this.getPlan()
      },
      getChapter() {
        tree().then(data => {
          this.chapter = data
        })
      },
      getCourseType() {
        typeTree().then(data => {
          this.courseType = data
        })
      },
      getPlan() {
        getPlanList().then(data => {
          this.planList = data
        })
      },
      getTeacher() {
        findUser(this.teacher).then(data => {
          this.teacherList = data
        })
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .el-dialog-div {
    height: 55vh;
    overflow-x: hidden;
  }
</style>
